package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.CustomException;
import com.itheima.common.R;
import com.itheima.entity.Category;
import com.itheima.entity.Dish;
import com.itheima.entity.Setmeal;
import com.itheima.mapper.CategoryMapper;
import com.itheima.service.CategoryService;
import com.itheima.service.DishService;
import com.itheima.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private DishService dishService;
    @Autowired
    private SetmealService setmealService;
    //新增菜品
    public R<String> add(@RequestBody Category category){
        categoryMapper.insert (category);
        return R.success ("新增分类成功");
    }
    //分页查询
    public R<Page> page(int page, int pageSize){
        Page<Category> pageInfo=new Page<> (page,pageSize);
        LambdaQueryWrapper<Category> qw=new LambdaQueryWrapper<> ();
        /*按照分类排序*/
        qw.orderByAsc (Category::getSort);
       categoryMapper.selectPage (pageInfo,qw);
        return R.success (pageInfo);

    }
//根据id删除分类，删除之前需要进行判断,关联了就不能删
    //重写的一个方法
    @Override
    public void remote(Long id) {
       //判断是否关联菜品
        LambdaQueryWrapper<Dish> dqw=new LambdaQueryWrapper<> ();
        dqw.eq (Dish::getCategoryId,id);
        int count=dishService.count (dqw);
        if(count>0){
            //抛出一个自定义异常
           throw new CustomException ("当前分类下关联了菜品，不能删除");
        }
        //判断是否关联套餐
        LambdaQueryWrapper<Setmeal> sqw=new LambdaQueryWrapper<> ();
        sqw.eq (Setmeal::getCategoryId,id);
        int count1=setmealService.count (sqw);
        if(count1>0){
            throw new CustomException("当前分类下关联了套餐，不能删除");
        }
        //正常删除
        super.removeById (id);
    }
    //修改
    public R<String>update(@RequestBody Category category){
        categoryMapper.updateById (category);
        return R.success("修改分类信息成功");
    }
    //根据条件查询分类数据
    //新增菜品的下拉列表
    public R<List<Category>> list(Category category){
        LambdaQueryWrapper<Category> qw=new LambdaQueryWrapper<> ();
        //条件为：菜品类型不为空
        qw.eq (category.getType ()!=null,Category::getType,category.getType ());
        //先按照菜品类型升序，再按照更新时间降序
        qw.orderByAsc (Category::getSort).orderByDesc (Category::getUpdateTime);
        List<Category> list=categoryMapper.selectList(qw);
        return R.success (list);

    }
}
